"""
Python is a programming language. Python is easy to learn. Python is widely used.
统计"Python"出现的次数

with open("files\\test.txt","r",encoding="utf-8") as f:
    res = f.read()
    print(res)
print(res.count('Python'))
"""

"""with open("files\\test.txt","r",encoding="utf-8") as f:
    res = f.read()
    print(res)

string = "Python is a programming language. Python is easy to learn. Python is widely used."
string_list = string.split("\n")
print(string_list)
count = 0
for line in string_list:
    count +=1
print(count)
"""


"""with open("files\\test.txt","r",encoding="utf-8") as f:
    res = f.read()
    print(res)
key = print(input("请输入关键字:"))
for line in res:
    if line == key:
        print(line)
    else: print("未找到相关记录")
# 更改数据
f = open("files\\test1.txt","r",encoding ="utf-8" )
fw = f.read()
fw = fw.replace("222","666")
print(fw)
"""


"""ef search_keyword_in_file(file_path, keyword):
    found = False
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
        for i, line in enumerate(lines, 1):
            if keyword.lower() in line.lower():
                print(f"行 {i}: {line.strip()}")
                found = True
    
    if not found:
        print("未找到关键字")

# 主程序
if __name__ == "__main__":
    file_path = input("请输入文件路径: ")
    keyword = input("请输入要搜索的关键字: ")
    search_keyword_in_file(file_path, keyword)
"""


#with open("files\\test2.txt","w",encoding = "utf-8") as f:
#    s= """ 2023-10-01 晴\n今天学习了python的文件操作! """
#    f.write(s)
#print("日记写入完成")


"""
date = input("请输入今天的日期：")
weather = input("请输入今天的天气：")
result = input("请输入今日心情或总结：")
with open("files\\test3.txt","a",encoding = "utf-8") as f:
    f.write(f"{date} {weather}\n")
    f.write(f"{result.replace(',','\n\n')}")
"""



with open("files\\bil.txt","r+",encoding = "utf-8") as f, open('files\\bil.txt.bak',"w",encoding = 'utf-8') as f_bak:
    #备份
    res = f.read()
    f_bak.write(res)

    # 内容删除
    s = ""
    for line in res.split('\n'):
        # 如果找不到返回-1
        if line.find("测试") == -1:
            s += line + '\n'
    
    #回旋指针  
    #用于将文件指针移动到文件的指定位置。这里的 f 是一个已打开的文件对象，seek() 方法的参数指定了移动的字节数。
    #适用场景：1.读取文件多次：当你已经读取了文件的内容，想要再次从头开始读取时
    #2.在写入前清空文件：当你想要覆盖文件内容而不是追加时
    #3.检查文件内容：在写入前查看文件的当前内容
    f.seek(0)
    #清空内容
    f.truncate()

    #写入新内容
    f.write(s)





